package com.panda.web.utils.task;

import com.aliyun.apache.hc.client5.http.classic.methods.HttpGet;


import com.aliyun.apache.hc.client5.http.classic.methods.HttpPost;
import com.aliyun.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import com.aliyun.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import com.aliyun.apache.hc.client5.http.impl.classic.HttpClients;
import com.aliyun.apache.hc.core5.http.ContentType;
import com.aliyun.apache.hc.core5.http.HttpEntity;
import com.aliyun.apache.hc.core5.http.io.entity.EntityUtils;

import com.aliyun.apache.hc.core5.http.io.entity.StringEntity;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.panda.web.entity.wechat.WechatUser;
import com.panda.web.mapper.wechat.WechatUserMapper;
import com.panda.web.utils.WeChatUtlis;
import lombok.extern.slf4j.Slf4j;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class TuSongTask {

    @Value("${gzh.api.app-id}")
    private String appId; //AppID
    @Value("${gzh.api.app_secret}")
    private String appSecret; //AppSecret
    @Autowired
    WeChatUtlis weChatUtlis;
    @Autowired
   private static WechatUserMapper wechatUserMapper;

    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + "wx83de228493c38c1c" + "&secret=" + "c9722f9217d91fda34f8667a56ae563b";


    public static void main(String[] args) {
        //TODO 批量获取 关注公众号的openid 和 unionid  跟数据库数据对比 替换
        //批量替换
        try {
            // 调用方法获取 access_token
            String accessToken = getAccessToken();  //获取的微信公众号的access_token
            List<String> stringList = getAllSubscribedOpenIds(accessToken);
            List<JSONObject> jsonObjects = batchGetUserInfos(accessToken,stringList);
            for (JSONObject jsonObject : jsonObjects) {
                String openid = jsonObject.getString("openid");
                String unionid = jsonObject.getString("unionid");
                WechatUser wechatUser = wechatUserMapper.findByOfficialOpenid(openid);
                if (wechatUser!=null){
                    wechatUser.setUnionid(unionid);
                    wechatUserMapper.updateById(wechatUser);
                }

            }

//            if (stringList != null && !stringList.isEmpty()) {
//                log.info("size: " + stringList.size());
//                for (String openId : stringList) {
//                    // 拉取用户信息(需scope为 snsapi_userinfo)
//                    StringBuilder builder1 = new StringBuilder("https://api.weixin.qq.com/sns/userinfo?access_token=");
//                    builder1.append(accessToken);
//                    builder1.append("&openid=");
//                    builder1.append(openId);
//                    builder1.append("&lang=zh_CN");
//
//                    // 发送HTTP请求获取用户信息
//                    String userInfo = WeChatUtlis.httpGetTest(builder1.toString());
//
//                    com.alibaba.fastjson2.JSONObject info = com.alibaba.fastjson2.JSONObject.parse(userInfo);
//                    String nickname = info.getString("nickname");
//                    String sex = info.getString("sex"); // 1时是男性，值为2时是女性，值为0时是未知
//                    String headimgurl = info.getString("headimgurl");
//                    String unionid = info.getString("unionid");
//                    log.info("unionid:" + unionid + "openid:" + openId);
//
//                }
//            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static String getAccessToken() throws Exception {
        URL url = new URL(ACCESS_TOKEN_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 使用 Gson 解析 JSON
            JsonParser parser = new JsonParser();
            JsonObject jsonObject = parser.parse(response.toString()).getAsJsonObject();

            // 检查是否有 access_token 字段
            if (jsonObject.has("access_token")) {
                return jsonObject.get("access_token").getAsString();
            } else {
                // 如果返回错误信息，打印错误码和错误信息
                if (jsonObject.has("errcode")) {
                    int errcode = jsonObject.get("errcode").getAsInt();
                    String errmsg = jsonObject.get("errmsg").getAsString();
                    throw new Exception("微信返回错误: errcode=" + errcode + ", errmsg=" + errmsg);
                } else {
                    throw new Exception("微信返回的数据格式不正确: " + response.toString());
                }
            }
        } else {
            throw new Exception("Failed to get access token. Response code: " + responseCode);
        }
    }

    /**
     * 获取所有关注用户的OpenID列表
     */
    private static List<String> getAllSubscribedOpenIds(String accessToken) throws Exception {
        List<String> openIds = new ArrayList<>();
        String nextOpenId = "";

        do {
            String url = "https://api.weixin.qq.com/cgi-bin/user/get" +
                    "?access_token=" + accessToken +
                    "&next_openid=" + nextOpenId;

            try (CloseableHttpClient httpClient = HttpClients.createDefault();
                 CloseableHttpResponse response = httpClient.execute(new HttpGet(url))) {

                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                JSONObject json = new JSONObject(result);

                if (json.has("data") && json.getJSONObject("data").has("openid")) {
                    JSONArray openidArray = json.getJSONObject("data").getJSONArray("openid");
                    for (int i = 0; i < openidArray.length(); i++) {
                        openIds.add(openidArray.getString(i));
                    }
                }

                // 检查是否有下一页
                nextOpenId = json.optString("next_openid", "");

            } catch (Exception e) {
                e.printStackTrace();
                break;
            }

        } while (!nextOpenId.isEmpty());

        return openIds;
    }

    /**
     * 批量获取用户详细信息（每次最多100个）
     */
    private static List<JSONObject> batchGetUserInfos(String accessToken, List<String> openIds) throws Exception {
        List<JSONObject> userInfos = new ArrayList<>();
        String url = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=" + accessToken;

        // 微信API限制每次最多查询100个用户
        int batchSize = 100;
        int totalUsers = openIds.size();

        for (int i = 0; i < totalUsers; i += batchSize) {
            int end = Math.min(i + batchSize, totalUsers);
            List<String> batch = openIds.subList(i, end);

            // 构建请求体
            JSONObject requestBody = new JSONObject();
            JSONArray userList = new JSONArray();

            for (String openid : batch) {
                JSONObject user = new JSONObject();
                user.put("openid", openid);
                user.put("lang", "zh_CN"); // 语言设置
                userList.put(user);
            }

            requestBody.put("user_list", userList);

            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                HttpPost httpPost = new HttpPost(url);
                httpPost.setHeader("Content-Type", "application/json");
                httpPost.setEntity(new StringEntity(requestBody.toString(), ContentType.parse("UTF-8")));

                try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                    HttpEntity entity = response.getEntity();
                    String result = EntityUtils.toString(entity);
                    JSONObject json = new JSONObject(result);

                    if (json.has("user_info_list")) {
                        JSONArray infoList = json.getJSONArray("user_info_list");
                        for (int j = 0; j < infoList.length(); j++) {
                            userInfos.add(infoList.getJSONObject(j));
                        }
                    } else {
                        System.err.println("批量获取用户信息失败: " + json);
                    }
                }
            }
        }

        return userInfos;
    }

}
